#include "timer.h"
#include <iostream>
#include <sys/time.h>

mytimer::mytimer(requestData *_request_data, int timeout) :
        request_data(_request_data), deleted(false) //构造函数,设置绝对过期时间
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    expired_time = 1000 * (tv.tv_sec) + (tv.tv_usec) / 1000 + timeout;
    //std::cout<<"timer construct!"<<std::endl;
}

mytimer::~mytimer() {
    //std::cout << "~mytimer(), ";
    if (request_data != nullptr) {
        //std::cout << "request_data=" << request_data << std::endl;
        delete request_data;
        request_data = NULL;
    }
}

bool mytimer::is_expire() { //如果过期自动设置删除标志位
    struct timeval tv;
    gettimeofday(&tv, NULL);
    long cur = 1000 * (tv.tv_sec) + (tv.tv_usec) / 1000;
    if (cur < expired_time) {
        return false;
    } else {
        deleted = true;
        return true;
    }
}

bool mytimer::is_deleted() {
    return deleted;
}

void mytimer::set_deleted() {  //删除定时器，是将定时器与请求类分离
    request_data = nullptr;
    deleted = true;
}

time_t mytimer::getExpTime() const {
    return expired_time;
}

bool timerCmp::operator()(const mytimer *a, const mytimer *b) const { //特别注意小顶堆实现
    return a->getExpTime() > b->getExpTime();
}

